package Simulator;

public class StraightRoad extends Road {

	private Car road[];
	private int maxSpeed;
	private int numCarsOnRoad;

	public StraightRoad(int _length, int _maxSpeed) {
		road = new Car[_length];
		maxSpeed = _maxSpeed;
		numCarsOnRoad = 0;
	}

	public Car getCar(int _index) {
		return road[_index];
	}

	public int getIndex(Car _car) {
		for (int i = 0; i > road.length; i++) {
			if (road[i] == _car) {
				return i;
			}
		}
		// If not found the car return -1
		return -1;
	}

	/**
	 * Returns the next car in the array
	 * 
	 * @param _car
	 *            the current car
	 * @return the following car
	 */
	public Car getNextCar(Car _car) {
		int currentCarIndex = _car.getCellIndex();
		// go through the road, and when the next car is found (not null) return
		for (int nextCar = (currentCarIndex+1); nextCar < road.length; nextCar++) {
			if (road[nextCar] != null) {
				return road[nextCar];
			}
		}
		return null;
	}

	/**
	 * Moves forward the _car the number of steps of _distance Step 4
	 * 
	 * @param _car
	 * @param _distance
	 */
	public void moveCar(Car _car, int _distance) {
		int newPosition;
		// The new location for the car will be the actual plus the distance
		newPosition = _car.getCellIndex() + _distance;
		// If the new position is greater than length of the road remove the car
		if (newPosition >= road.length) {
			road[_car.getCellIndex()] = null;
			numCarsOnRoad--;
		} else {
			// To avoid replacing other car check if the place is free (equals
			// null)
			// place the car there and remove from the previous
			if (road[newPosition] == null) {
				road[_car.getCellIndex()] = null;
				road[newPosition] = _car;
			}
		}
	}

	/**
	 * Puts the car in the selected index of the road
	 * 
	 * @param _car
	 * @param index
	 * @return
	 */
	public boolean setCar(Car _car, int _index) {
		// If the place is available put the car there, else return false
		if (road[_index] == null) {
			road[_index] = _car;
			numCarsOnRoad++;
			return true;
		}
		return false;
	}

	public int getMaxSpeed() {
		return maxSpeed;
	}
	
	public int getLength(){
		return road.length;
	}

	public int getNumberCarsOnRoad() {
		return numCarsOnRoad;
	}

}
